package sisdroid.client;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import sisdroid.client.db.DemoDbAdapter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;;

public class SisActivity extends Activity
{
	java.util.Timer timer;
	
	NetDiscoverer nd = null;
	TextView	tv	= null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	try
    	{
    		super.onCreate( savedInstanceState );
    		setContentView( sisdroid.client.R.layout.main );
    	}
    	catch ( Exception e )
    	{
    		tv = null;
    	}
        
        tv = (TextView)findViewById( sisdroid.client.R.id.TextView );
        Button 		but = (Button)findViewById( sisdroid.client.R.id.Update );
        
        
        
        nd = new CompositeDiscoverer( new WifiDiscoverer( this ), new BluetoothDiscoverer( this ) );
        nd = new CompositeDiscoverer( new CellIdDiscoverer( this ), nd );
        nd = new CompositeDiscoverer( new GpsDiscoverer( this ), nd );
        
        java.util.TimerTask tt = new TimerTask()
        {			
			@Override
			public void run()
			{
				updateZones( false );
				
			}
		};
		
		timer = new Timer();
		
		timer.scheduleAtFixedRate(tt, 30 * 1000, 1000 * 60 * 3 );
        
        but.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				updateZones( true );
			}
		});
        
        
    }
    void updateZones( boolean updateGui )
    {
    	sisdroid.client.db.DemoDbAdapter adapter = null; 
		try
		{
			
			adapter = new DemoDbAdapter( this );
			
			adapter.open();
			
			java.util.Date now = new Date();
			if ( updateGui )
				tv.setText( "Scan result @ " + now.toGMTString() + ": \n" );
	        
			long lowid = -1;
			
			for ( sisdroid.client.model.Location s : nd.getNetIDS() )
	        {
				long thisid = adapter.createNet( s );
				
				if ( lowid == -1 ) lowid = thisid;
				
	        	adapter.createLink( lowid, thisid );
				
	        	if ( updateGui )
	        		tv.setText( tv.getText() + " : " + s.toString() );
	        }
	     
		}
		catch ( Exception e )
		{
			if ( updateGui )
				tv.setText( e.getMessage() );
		}	
		finally
		{
			if ( adapter != null )
				adapter.close();
		}
    }
}